package com.ht.demo.admin.controller.generator;

import cn.hutool.core.convert.Convert;
import com.ht.demo.common.pojo.qto.gen.GenTable;
import com.ht.demo.common.pojo.qto.gen.GenTableColumn;
import com.ht.demo.common.pojo.qto.gen.GenTableQTO;
import com.ht.demo.common.appexception.ResultData;
import com.ht.demo.common.page.PageBO;
import com.ht.demo.service.manager.gen.IGenTableColumnService;
import com.ht.demo.service.manager.gen.IGenTableService;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author hdengxian
 * @Date 2023/7/14 8:53
 */
@RestController
@RequestMapping("${basePath}")
public class GeneratorController {
    @Resource
    private IGenTableService iGenTableService;
    @Resource
    private IGenTableColumnService iGenTableColumnService;

    /**
     * 分页查询
     * @param qto
     * @return
     */
    @GetMapping("/tool/gen/list")
    public ResultData findForPage(GenTableQTO qto) {
        return new ResultData(iGenTableService.selectGenTableList(qto));
    }

    /**
     * 修改
     * @param talbleId
     * @return
     */
    @GetMapping(value = "/tool/gen/{talbleId}")
    public ResultData getInfo(@PathVariable Long talbleId) {
        GenTable table = iGenTableService.selectGenTableById(talbleId);
        List<GenTable> tables = iGenTableService.selectGenTableAll();
        List<GenTableColumn> list = iGenTableColumnService.selectGenTableColumnListByTableId(talbleId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("info", table);
        map.put("rows", list);
        map.put("tables", tables);

        ResultData resultData = new ResultData();
        resultData.setExtraMap(map);
        return resultData;
    }

    /**
     * 查询数据库列表
     * @param qto
     * @return
     */
    @GetMapping("/tool/gen/db/list")
    public ResultData dataList(GenTableQTO qto) {
        return new ResultData(iGenTableService.selectDbTableList(qto));
    }

    /**
     * 查询数据表字段列表
     * @param tableId
     * @return
     */
    @GetMapping(value = "/tool/gen/column/{talbleId}")
    public ResultData columnList(Long tableId) {
        List<GenTableColumn> list = iGenTableColumnService.selectGenTableColumnListByTableId(tableId);
        PageBO<GenTableColumn> pageBO = new PageBO<>();
        pageBO.setData(list, list.size());
        return new ResultData(pageBO);
    }

    /**
     * 导入表结构（保存）
     * @param tables
     * @return
     */
    @PostMapping("/tool/gen/importTable")
    public ResultData importTableSave(String tables) {
        String[] tableNames = Convert.toStrArray(tables);
        // 查询表信息
        List<GenTable> tableList = iGenTableService.selectDbTableListByNames(tableNames);
        iGenTableService.importGenTable(tableList);
        return new ResultData();
    }

    @DeleteMapping("/tool/gen/{tableIds}")
    public ResultData remove(@PathVariable Long[] tableIds) {
        iGenTableService.deleteGenTableByIds(tableIds);
        return new ResultData();
    }

    /**
     * 预览代码
     */
    @GetMapping("/tool/gen/preview/{tableId}")
    public ResultData preview(@PathVariable("tableId") Long tableId) throws IOException {
        Map<String, String> dataMap = iGenTableService.previewCode(tableId);
        ResultData resultData = new ResultData();
        resultData.setExtraMap(dataMap);
        return resultData;
    }

    /**
     * 生成代码（下载方式）
     */
    @GetMapping("/tool/gen/download/{tableName}")
    public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException {
        byte[] data = iGenTableService.downloadCode(tableName);
        genCode(response, data);
    }

    /**
     * 批量生成代码
     * （下载方式）
     * @param response
     * @param tables
     * @throws IOException
     */
    @GetMapping("/tool/gen/batchGenCode")
    public void batchGenCode(HttpServletResponse response, String tables) throws IOException {
        String[] tableNames = Convert.toStrArray(tables);
        byte[] data = iGenTableService.downloadCode(tableNames);
        genCode(response, data);
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException {
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"generator.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}
